<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">科室名称</label>
        <el-input v-model="query.name" clearable placeholder="科室名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        append-to-body
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="580px"
      >
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="上级科室" prop="parent_id">
            <tree-select
              v-model="form.parent_id"
              :options="departments"
              :load-options="loadDepartment"
              style="width: 450px;"
              placeholder="选择上级科室"
            />
          </el-form-item>
          <el-form-item label="科室名称" prop="name">
            <el-input v-model="form.name" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="form.description" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        lazy
        :load="getDepartmen"
        :data="crud.data"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        row-key="departmentId"
        size="small"
        style="width: 100%;"
        @select="crud.selectChange"
        @select-all="crud.selectAllChange"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column :show-overflow-tooltip="true" prop="name" label="科室名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="updateTime" label="更新时间" />
        <el-table-column v-if="checkPer(['admin','sysDepartment:edit','sysDepartment:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudSysDepartment from '@/api/system/sysDepartment'
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation.vue'
import crudOperation from '@crud/CRUD.operation.vue'
import udOperation from '@crud/UD.operation.vue'
import pagination from '@crud/Pagination.vue'

const defaultForm = { parent_id: null, parentId: null, departmentId: null, name: null, description: null, createTime: null, updateTime: null }
export default {
  name: 'SysDepartment',
  components: { TreeSelect, pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: '科室管理',
      url: 'api/sysDepartment',
      idField: 'departmentId',
      sort: 'departmentId,desc',
      crudMethod: { ...crudSysDepartment }})
  },
  data() {
    return {
      departments: [],
      permission: {
        add: ['admin', 'sysDepartment:add'],
        edit: ['admin', 'sysDepartment:edit'],
        del: ['admin', 'sysDepartment:del']
      },
      rules: {
        name: [
          { required: true, message: '科室名称不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'name', display_name: '科室名称' }
      ]
    }
  },
  methods: {
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](form) {
      this.departments = []
      if (form.id != null) {
        if (form.parent_id === null) {
          form.parentId = 0
        }
        this.getSupDepts(form.id)
      } else {
        this.departments.push({ id: 0, label: '顶级科室', children: null })
      }
    },
    getDepartmen(tree, treeNode, resolve) {
      const params = { parentId: tree.departmentId }
      setTimeout(() => {
        crudSysDepartment.getDepartment(params).then(res => {
          resolve(res.content)
        })
      }, 100)
    },
    loadDepartment({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        crudSysDepartment.getDepartmentsTree(parentNode.id).then(res => {
          // 遍历res 然后把res的name赋值成每个值的label
          res.forEach(item => {
            item.label = item.name
            item.id = item.departmentId
            if (item.subCount === 0) {
              item.hasChildren = true
              item.leaf = true
            } else {
              item.hasChildren = false
              item.leaf = false
            }
          })
          parentNode.children = res.map(function(obj) {
            if (!obj.leaf) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 100)
        })
      }
    },
    getSupDepts(id) {
      crudSysDepartment.getDepartmentsTree(id).then(res => {
        res.forEach(item => {
          item.label = item.name
          item.id = item.departmentId
          if (item.subCount === 0) {
            item.hasChildren = true
          } else {
            item.hasChildren = false
          }
        })
        console.log(res)
        const children = res.map(function(obj) {
          if (!obj.leaf && !obj.children) {
            obj.children = null
          }
          return obj
        })
        this.departments = [{ id: 0, label: '顶级科室', children: children }]
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
::v-deep .vue-treeselect__control,::v-deep .vue-treeselect__placeholder,::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
